var net = require("net");
var exec = require("child_process").exec;

function asyncRepeat(callback, onDone) {
  callback(function () {
    asyncRepeat(callback, onDone);
  }, onDone);
}

function findFreePort(start, hostname, callback) {
  var end = 65536
  var pivot = start //Math.floor(Math.random() * (end - start)) + start;
  var port = pivot;
  asyncRepeat(function (next, done) {
    var stream = net.createConnection(port, hostname);

    stream.on("connect", function () {
      stream.destroy();
      port++;
      if (port > end)
        port = start;

      if (port == pivot)
        done("Could not find free port.");

      next();
    });

    stream.on("error", function () {
      done();
    });
  }, function (err) {
    callback(err, port);
  });
};
function isPortOpen(hostname, port, timeout = 1000, callback) {
  var stream = net.createConnection(port, hostname);

  stream.on("connect", function () {
    clearTimeout(id);
    stream.destroy();
    callback && callback(true);
  });

  stream.on("error", function () {
    clearTimeout(id);
    stream.destroy();
    callback && callback(false);
  });

  var id = setTimeout(function () {
    stream.destroy();
    callback && callback(false);
  }, timeout);
};


function getHostName(callback) {
  exec("hostname", function (error, stdout, stderr) {
    if (error)
      return callback(stderr);
    callback(null, stdout.toString().split("\n")[0]);
  });
};



exports.findFreePort = findFreePort
exports.isPortOpen = isPortOpen
exports.getHostName = getHostName


getHostName((err, hostname) => {
  console.log(hostname)
  findFreePort(80, null, (err, port) => {
    console.log(err, port)
  })
})
